package com.example.networkutil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import utils.IOHandler;
import android.os.Environment;
import android.util.Log;


public class FtpHandler {

	public static FTPClient mFTPClient = null;
	public static String ADDRESS = null;
	public static String LOGIN = null;
	public static String PASS = null;
	public static String IN = null;
	public static String OUT = null;
	
	public static void getAuthdata() {
		
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			File pPath = Environment.getExternalStorageDirectory();
			try {
				if (!(new File (pPath.getAbsolutePath()+ "/Suppliers").exists())){
					Log.d("IO", "Directory was created");
					new File (pPath.getAbsolutePath()+ "/Suppliers").mkdir();
				}
				File pFile = new File(pPath.getAbsolutePath()+ "/Suppliers", "auth.cfg");
				if (IOHandler.checkFile("auth.cfg")) {
					InputStream fis;
					BufferedReader br;
					String line;
					int linenumber = 1;
					fis = new FileInputStream(pFile);

					br = new BufferedReader(new InputStreamReader(fis,
							Charset.forName("UTF-8")));
					while ((line = br.readLine()) != null) {
						switch (linenumber) {
						case 1:
							ADDRESS = line;
							break;
						case 2:
							LOGIN = line;
							break;
						case 3:
							PASS = line;
							break;
						case 4:
							IN = line;
							break;	
						case 5:
							OUT = line;
							break;	
						default:
							Log.v("IO:", " EOF! ");
							break;
						}
						linenumber++;
					}

					br.close();
					Log.d("IO", "AUTH DATA WAS READ FROM STORAGE");
					
				} else {
					pFile.createNewFile();
					PrintWriter out = new PrintWriter(pFile);
					out.println("miles.timeweb.ru");
					out.println("ilovemebel_exch1c");
					out.println("exchange2013");
					out.println("suppliers_in");
					out.print("suppliers_out");
					ADDRESS = "miles.timeweb.ru";
					LOGIN = "ilovemebel_exch1c";
					PASS = "exchange2013";
					IN = "suppliers_in";
					OUT = "suppliers_out";
					out.close();
				}

			} catch (IOException e) {
				Log.d("IO", "Can't get External Storage");
			}
		}

	}

	public static boolean ftpConnect() {
		if (ADDRESS == null || LOGIN == null || PASS == null) {
			getAuthdata();
		}

		try {
			mFTPClient = new FTPClient();
			mFTPClient.setConnectTimeout(10000);
			mFTPClient.connect(ADDRESS, 21);
			if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
				boolean status = mFTPClient.login(LOGIN, PASS);
				mFTPClient.enterLocalPassiveMode();
				mFTPClient
						.setFileTransferMode(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);

				return status;
			}
		} catch (Exception e) {
			Log.d("FTP", "Error: could not connect to host " + ADDRESS);
		}

		return false;
	}

	public static boolean ftpDisconnect() {
		try {
			mFTPClient.logout();
			mFTPClient.disconnect();
			mFTPClient = null;
			return true;
		} catch (Exception e) {
			Log.d("FTP CLIENT",
					"Error occurred while disconnecting from ftp server.");
		}

		return false;
	}

	public static String ftpGetCurrentWorkingDirectory() {
		try {
			String workingDir = mFTPClient.printWorkingDirectory();
			return workingDir;
		} catch (Exception e) {
			Log.d("FTP CLIENT",
					"Error: could not get current working directory.");
		}

		return null;
	}

	// Method to change working directory:

	public static boolean ftpChangeDirectory(String directory_path) {
		boolean status = false;
		try {
			mFTPClient.changeWorkingDirectory(directory_path);
			status = true;
		} catch (Exception e) {
			Log.d("FTP CLIENT", "Error: could not change directory to "
					+ directory_path);
		}

		return status;
	}

	// Method to list all files in a directory:

	public static void ftpPrintFilesList(String dir_path) {
		try {
			FTPFile[] ftpFiles = mFTPClient.listFiles(dir_path);
			int length = ftpFiles.length;

			for (int i = 0; i < length; i++) {
				String name = ftpFiles[i].getName();
				boolean isFile = ftpFiles[i].isFile();

				if (isFile) {
					Log.i("FTP CLIENT", "File : " + name);
				} else {
					Log.i("FTP CLIENT", "Directory : " + name);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Method to create new directory:

	public static boolean ftpMakeDirectory(String new_dir_path) {
		try {
			boolean status = mFTPClient.makeDirectory(new_dir_path);
			return status;
		} catch (Exception e) {
			Log.d("FTP CLIENT", "Error: could not create new directory named "
					+ new_dir_path);
		}

		return false;
	}

	// Method to delete/remove a directory:

	public static boolean ftpRemoveDirectory(String dir_path) {
		try {
			boolean status = mFTPClient.removeDirectory(dir_path);
			return status;
		} catch (Exception e) {
			Log.d("FTP CLIENT", "Error: could not remove directory named "
					+ dir_path);
		}

		return false;
	}

	// Method to delete a file:

	public static boolean ftpRemoveFile(String filePath) {
		try {
			boolean status = mFTPClient.deleteFile(filePath);
			return status;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	// Method to rename a file:

	public static boolean ftpRenameFile(String from, String to) {
		try {
			boolean status = mFTPClient.rename(from, to);
			return status;
		} catch (Exception e) {
			Log.d("FTP CLIENT", "Could not rename file: " + from + " to: " + to);
		}

		return false;
	}

	
	
	  public static InputStream ftpDownload(String dir ,String filename) { 
	  InputStream is = null; 
	  try {
		//  Log.d("status FTP:",mFTPClient.getStatus());
	  is = mFTPClient.retrieveFileStream( dir+"/"+filename+".xml"); 
	  mFTPClient.completePendingCommand();
	 // Log.d("status FTP:",mFTPClient.getStatus());
	  if(is!=null){ Log.v("FTPTask","XML : Done!"); }
	  
	  
	  } catch (Exception e) { e.printStackTrace(); Log.d("FTP DOWNLOAD", "download failed"); return null;}
	  
	  return is; }
	
	// Method to upload a file to FTP server:
	public static boolean ftpUpload(String srcFilePath, String desFileName,
			String desDirectory) {
		boolean status = false;
		
		try {
			FileInputStream srcFileStream = new FileInputStream(IOHandler.getFilePath(srcFilePath));

			// change working directory to the destination directory
			if (ftpChangeDirectory(desDirectory)) {
				status = mFTPClient.storeFile(desFileName, srcFileStream);
			}

			srcFileStream.close();
			mFTPClient.logout();
			mFTPClient.disconnect();
			mFTPClient = null;
			return status;
		} catch (Exception e) {
			Log.d("FTP CLIENT", "upload failed");
		}

		return status;
	}

}
